package com.ty.xiaoyu.controller;

import com.ty.xiaoyu.entity.*;
import com.ty.xiaoyu.exception.HomePageRotationChartOperationException;
import com.ty.xiaoyu.exception.SearchHistoryOperationException;
import com.ty.xiaoyu.exception.TopicOperationException;
import com.ty.xiaoyu.util.MyTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/homePage")
@Slf4j
public class HomePageController extends BaseController {

    private final String GREATId = "103";

    /**
     * 获取轮播图
     * @return 轮播图列表
     */
    @GetMapping("/getRotationChart")
    private Map<String, Object> getRotationChart() {
        log.info(MyTimeUtil.nowTime() + "=== getRotationChart star ===");
        Map<String, Object> modelMap = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        List<HomePageRotationChart> rotationChartList = null;
        try {
            rotationChartList = homePageRotationChartService.getHomePageRotationChartList();
        } catch (HomePageRotationChartOperationException e) {
            modelMap.put("code", 101);
            modelMap.put("msg", e.getMessage());
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== getRotationChart error 未找到轮播图 ===" + e.getMessage());
            return modelMap;
        }
        data.put("rotationChartList",rotationChartList);
        modelMap.put("code", 0);
        modelMap.put("msg", "成功");
        modelMap.put("data", data);
        log.info(MyTimeUtil.nowTime() + "=== getRotationChart end ===");
        return modelMap;
    }

    /**
     * 获取帖子列表
     * @param pageIndex 页数
     * @param pageSize 页面容量
     * @param condition 查询方式，0：发帖时间，1：最后回复时间
     * @return topicList列表
     */
    @GetMapping("/getList")
    private Map<String, Object> getList(@RequestParam(value = "pageIndex", defaultValue = "0") Integer pageIndex,
                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                        @RequestParam(value = "condition", defaultValue = "0") Integer condition) {
        log.info(new Date() + "=== getList star ===");
        Map<String, Object> modelMap = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        List<Topic> topicList = null;
        try {
            if (condition == 1) {
                topicList = topicService.getListByLastTime(pageIndex, pageSize);
            } else {
                topicList = topicService.getListByReleaseTime(pageIndex, pageSize);
            }
        } catch (TopicOperationException e) {
            modelMap.put("code", 102);
            modelMap.put("msg", e.getMessage());
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== getList error 未找到帖子 ===" + e.getMessage());
            return modelMap;
        }
        for (Topic topic : topicList) {
            // 获取帖子图片
            List<TopicImage> topicImageList = topicService.getTopicImageList(topic.getTopicId());
            if (topicImageList.size() > 0) {
                topic.setTopicImageList(topicImageList);
            }
            // 获取贴子的回复数量
            topic.setReplyNum(replyService.getReplyNum(topic.getTopicId()));
            if (loginUser == null) {
                continue;
            }
            // 获取是否已点赞
            Great great = greatService.getGreatByTopicIdAndUserId(topic.getTopicId(), loginUser.getUserId());
            topic.setGreat(great != null && great.getGreatState() != 0);
        }
        data.put("topicList", topicList);
        Integer pageNum = (int)Math.ceil((double)topicService.queryTopicNum() / pageSize);
        data.put("pageNum", pageNum);
        modelMap.put("code", 0);
        modelMap.put("msg", "成功");
        modelMap.put("data", data);
        log.info(MyTimeUtil.nowTime() + "=== getList end ===");
        return modelMap;
    }

    /**
     * 搜索帖子
     * @param pageIndex 页数
     * @param pageSize 页面容量
     * @param content 关键字
     * @return topicList列表
     */
    @GetMapping("/search")
    private Map<String, Object> search(@RequestParam(value = "pageIndex", defaultValue = "0") Integer pageIndex,
                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                       @RequestParam("content") String content) {
        log.info(new Date() + "=== search star ===");
        Map<String, Object> modelMap = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        if ("".equals(content.trim())) {
            modelMap.put("code", 103);
            modelMap.put("msg", "参数为空");
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== search error 参数为空 ===");
            return modelMap;
        }
        List<String> condition = Arrays.asList(content.trim().split("\\s+"));
        List<Topic> topicList = null;
        try {
            topicList = topicService.getListByCondition(pageIndex, pageSize, condition);
        } catch (TopicOperationException e) {
            modelMap.put("code", 102);
            modelMap.put("msg", e.getMessage());
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== search error 未找到帖子 ===" + e.getMessage());
            return modelMap;
        }
        for (Topic topic : topicList) {
            List<TopicImage> topicImageList = topicService.getTopicImageList(topic.getTopicId());
            if (topicImageList.size() > 0) {
                topic.setTopicImageList(topicImageList);
            }
        }
        data.put("topicList", topicList);
        modelMap.put("code", 0);
        modelMap.put("msg", "成功");
        modelMap.put("data", data);
        // 未登录则不添加浏览记录
        if (loginUser == null) {
            log.info(MyTimeUtil.nowTime() + "=== search end ===");
            return modelMap;
        }
        // 新增搜索记录
        SearchHistory history = searchHistoryService.getSearchHistoryByUserIdAndSearchText(loginUser.getUserId(), content);
        if (history == null) {
            // 新增记录
            history = new SearchHistory();
            history.setUserId(loginUser.getUserId());
            history.setSearchText(content);
            try {
                searchHistoryService.addSearchHistory(history);
            } catch (SearchHistoryOperationException e) {
                modelMap.put("code", 105);
                modelMap.put("msg", e.getMessage());
                log.error(MyTimeUtil.nowTime() + "=== search error 添加搜索记录失败 ===" + e.getMessage());
                return modelMap;
            }
        } else {
            // 更新记录
            try {
                searchHistoryService.updateSearchHistoryByHistory(history);
            } catch (SearchHistoryOperationException e) {
                modelMap.put("code", 106);
                modelMap.put("msg", e.getMessage());
                log.error(MyTimeUtil.nowTime() + "=== search error 更新搜索记录失败 ===" + e.getMessage());
                return modelMap;
            }
        }
        log.info(MyTimeUtil.nowTime() + "=== search end ===");
        return modelMap;
    }

    /**
     * 根据用户id获取搜索记录
     * @param pageIndex 页数
     * @param pageSize 页面容量
     * @return 搜索列表
     */
    @GetMapping("/getSearchHistoryList")
    private Map<String, Object> getSearchHistoryList(@RequestParam(value = "pageIndex", defaultValue = "0") Integer pageIndex,
                                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        log.info(new Date() + "=== getSearchHistoryList star ===");
        Map<String, Object> modelMap = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        List<SearchHistory> historyListOfSearch = null;
        String userId = loginUser.getUserId();
        try {
            historyListOfSearch = searchHistoryService.getSearchHistoryByUserId(pageIndex, pageSize, userId);
        } catch (SearchHistoryOperationException e) {
            modelMap.put("code", 102);
            modelMap.put("msg", e.getMessage());
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== getSearchHistoryList error 更新搜索记录失败 ===" + e.getMessage());
            return modelMap;
        }
        data.put("historyListOfSearch", historyListOfSearch);
        modelMap.put("code", 0);
        modelMap.put("msg", "成功");
        modelMap.put("data", data);
        log.info(MyTimeUtil.nowTime() + "=== getSearchHistoryList end ===");
        return modelMap;
    }

    /**
     * 删除当前用户的全部搜索记录
     * @return
     */
    @DeleteMapping("/deleteSearchHistoryList")
    private Map<String, Object> deleteSearchHistoryList() {
        log.info(new Date() + "=== deleteSearchHistoryList star ===");
        Map<String, Object> modelMap = new HashMap<>();
        String userId = loginUser.getUserId();
        try {
            searchHistoryService.deleteAllSearchHistoryByUserId(userId);
        } catch (SearchHistoryOperationException e) {
            modelMap.put("code", 107);
            modelMap.put("msg", e.getMessage());
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== deleteSearchHistoryList error 更新搜索记录失败 ===" + e.getMessage());
            return modelMap;
        }
        modelMap.put("code", 0);
        modelMap.put("msg", "成功");
        modelMap.put("data", null);
        log.info(MyTimeUtil.nowTime() + "=== deleteSearchHistoryList end ===");
        return modelMap;
    }

}
